package com.source.barcodeMachineGrantAndRecovery.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.source.barcodeMachineGrantAndRecovery.VO.HouseMachineGrantList;
import com.source.barcodeMachineGrantAndRecovery.VO.HouseMachineGrantVO;
import com.source.barcodeMachineGrantAndRecovery.entity.HouseMachineGrant;
import com.source.barcodeMachineGrantAndRecovery.service.HouseMachineGrantService;
import com.source.baseData.entity.BarcodeMachine;
import com.source.baseData.service.BarcodeMachineService;
import com.source.utils.CommonResult;
import com.source.utils.DateUtils;
import com.source.utils.MyPage;
import com.source.utils.ResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author IceBerg777
 * @since 2021-04-14
 */

@Api(tags = "屠宰市场脚标机发放记录/总表信息管理 - 一级发放")
@RestController
@CrossOrigin
@RequestMapping("/barcodeMachineGrantAndRecovery/house-machine-grant")
public class HouseMachineGrantController {

    @Autowired
    private HouseMachineGrantService grantService;

    @Autowired
    private BarcodeMachineService machineService;

    @Autowired
    private DateUtils dateUtils;

    @ApiOperation("给屠宰市场发放新的脚标机【新租期、租金等】")
    @PostMapping("/add")
    public CommonResult<String> add(@RequestBody @Validated HouseMachineGrant machineGrant) {
        try {

            //给屠宰市场脚标机发放记录设置id
            machineGrant.setId(IdWorker.get32UUID());
            machineGrant.setStatus(0);

            //查找总表对应的脚标机【应该还需要更改脚标机状态表的userId】
            BarcodeMachine barcodeMachine = machineService.findByMachineNumber(machineGrant.getMachineNumber());

            //更新总表grantId、deliveryStatus的最新状态
            barcodeMachine.setHouseGrantId(machineGrant.getId());
            barcodeMachine.setDeliveryStatus("0");

            if (machineGrant.getIsHired() == 1) {
                //如果是买的，就设置一个比较大的时间
                Date date1 = dateUtils.stringToDate("3021-12-31");
                machineGrant.setExpiringDate(date1);
            }
            machineGrant.setStallsGrantId(null);
            machineGrant.setStallsRevokeId(null);
            //更新、保存进数据库
            grantService.save(machineGrant);

            machineService.updateById(barcodeMachine);

            return new CommonResult<String>(ResultEnum.SUCCESS);
//            if (machineService.updateById(barcodeMachine) && grantService.save(machineGrant)) {
//                return new CommonResult<String>(ResultEnum.SUCCESS);
//            } else {
//                return new CommonResult<String>(ResultEnum.ERROR);
//            }

        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常！");
        }
    }

    @ApiOperation("给屠宰市场【批量】发放新的脚标机")
    @PostMapping("/multiAdd")
    public CommonResult<String> multiAdd(@RequestBody @Validated HouseMachineGrantList machineGrantList){
        List<String> machineNumbers = machineGrantList.getMachineNumbers();
        try {
            for (String machineNumber : machineNumbers) {
                HouseMachineGrant machineGrant = new HouseMachineGrant();
                //copy进去，调用add接口
                BeanUtils.copyProperties(machineGrantList, machineGrant);

                machineGrant.setMachineNumber(machineNumber);
                add(machineGrant);
            }
            return new CommonResult<String>(ResultEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR);
        }

    }

    @ApiOperation("查找还没发放的脚标机 - 返回list集合")
    @GetMapping("/findUnGranted")
    public CommonResult<List<BarcodeMachine>> findUnGranted() {
        List<BarcodeMachine> list = machineService.findUnGranted();
        return new CommonResult<List<BarcodeMachine>>(ResultEnum.SUCCESS, list);
    }

    @ApiOperation("更新屠宰场发放记录")
    @PutMapping("/update")
    public CommonResult<String> update(@RequestBody HouseMachineGrant machineGrant) {
        try {
            if (grantService.updateById(machineGrant)) {
                return new CommonResult<String>(ResultEnum.SUCCESS);
            } else {
                return new CommonResult<String>(ResultEnum.ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常！");
        }
    }

    @ApiModelProperty("根据【主键id】删除屠宰场脚标机")
    @DeleteMapping("/deleteById/{id}")
    public CommonResult<String> deleteById(@PathVariable String id) {
        try {
            HouseMachineGrant byId = grantService.getById(id);
            String machineNumber = byId.getMachineNumber();
            if (grantService.removeById(id)) {

                //从屠宰场脚标机表删除之后，就相当于不给这个屠宰场发放了
                BarcodeMachine byMachineNumber = machineService.findByMachineNumber(machineNumber);

                //这里要判断移除的记录是不是和总表记录的一致！！
                if(byMachineNumber.getHouseGrantId().equals(byId.getId())){
                    byMachineNumber.setHouseGrantId(null);
                    byMachineNumber.setDeliveryStatus("1");
                    machineService.updateById(byMachineNumber);
                }
                //一致就需要更新总表的GrantId，不然就不需要处理。
                return new CommonResult<String>(ResultEnum.SUCCESS);
            } else {
                return new CommonResult<String>(ResultEnum.ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常");
        }
    }

    @ApiOperation("根据【主键id】查找屠宰市场脚标机发放类")
    @GetMapping("/findById/{id}")
    public CommonResult<HouseMachineGrantVO> findById(@PathVariable String id) {
        HouseMachineGrantVO grantVO = grantService.findById(id);
        return new CommonResult<>(ResultEnum.SUCCESS, grantVO);
    }

    @ApiOperation("查找所有 - 分页")
    @GetMapping("/findAll/{current}/{size}")
    public CommonResult findAll(@PathVariable Integer current, @PathVariable Integer size) {

        List<HouseMachineGrantVO> list = grantService.findAll();
        Page page = MyPage.list2Page(current, size, list);
        return new CommonResult<>(ResultEnum.SUCCESS, page);
    }

    @ApiOperation("模糊查找 - 分页")
    @GetMapping("/findByLike/{current}/{size}/{keyWord}")
    public CommonResult findByLike(@PathVariable Integer current, @PathVariable Integer size, @PathVariable String keyWord) {
        List<HouseMachineGrantVO> list = grantService.findByLike(keyWord);
        Page page = MyPage.list2Page(current, size, list);
        return new CommonResult<>(ResultEnum.SUCCESS, page);
    }

    @ApiOperation("去重查找所有 - 分页")
    @GetMapping("/findAllDistinct/{current}/{size}")
    public CommonResult findAllDistinct(@PathVariable Integer current, @PathVariable Integer size) {

        List<HouseMachineGrantVO> list = grantService.findAllDistinct();
        Page page = MyPage.list2Page(current, size, list);
        return new CommonResult<>(ResultEnum.SUCCESS, page);
    }

    @ApiOperation("去重模糊查找 - 分页")
    @GetMapping("/findDistinctByLike/{current}/{size}/{keyWord}")
    public CommonResult findDistinctByLike(@PathVariable Integer current, @PathVariable Integer size, @PathVariable String keyWord) {
        List<HouseMachineGrantVO> list = grantService.findDistinctByLike(keyWord);
        Page page = MyPage.list2Page(current, size, list);
        return new CommonResult<>(ResultEnum.SUCCESS, page);
    }


}

